package com.kt.thread.demo.model;

import org.omg.CORBA.TIMEOUT;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Author: kt
 * @CreateTime: 2021/3/13
 */
public class Server {
    private Thread worker;
    private boolean start;
    private BlockingQueue<ClientTask> clientTasks = new ArrayBlockingQueue<ClientTask>(16);
    private Map<String, String> dataMap = new HashMap<>();
    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 4, 60L,
            TimeUnit.SECONDS, new ArrayBlockingQueue<>(16), new ThreadPoolExecutor.DiscardPolicy());

    public synchronized void start() {
        if (!start) {
            start = true;
            worker = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        process();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }, "worker-thread");
            worker.start();
        }
    }

    public void send(ClientTask clientTask) {
        clientTasks.add(clientTask);
    }

    private void process() throws InterruptedException {
        for (; ; ) {
            ClientTask clientTask = clientTasks.take();
            processTask(clientTask);
        }
    }

    private void processTask(ClientTask clientTask) {
        System.out.println("线程"+Thread.currentThread().getName()+"在处理服务端数据");
        AbstractCommand command = clientTask.getCommand();
        String data;
        if (command.command() == Command.REDA) {
            data = dataMap.get(command.getKey());
        } else if (command.command() == Command.WRITE) {
            WriteCommand writeCommand = (WriteCommand) command;
            dataMap.put(writeCommand.getKey(), writeCommand.getData());
            data = "OK";
        } else {
            System.out.println("错误的指令...");
            return;
        }
        threadPoolExecutor.submit(new ServerTask(clientTask.getClient(), data));
    }
}
